﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace ImageDownLoad
{
    public partial class GetImgs : Form
    {
        public delegate void UpdateListBox(String str);
        private int imgCount = 0;
        private int imgSuccess = 0;
        private int imgFailed = 0;
        public GetImgs()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string file = textBox_file.Text;
            if (String.IsNullOrEmpty(file))
            {
                MessageBox.Show("CSV文件未选择!");
                return;
            }

            String savePath = textBox_savePath.Text;
            if (String.IsNullOrEmpty(savePath))
            {
                MessageBox.Show("保存路径未选择!");
                return;
            }

            Int16 threadPoolSize = Int16.Parse(textBox_ThreadPoolSize.Text);
            if (threadPoolSize > 10 || threadPoolSize < 1)
            {
                MessageBox.Show("线程池大小须在1-10之间!");
                return;
            }
          
            imgCount = 0; imgSuccess = 0; imgFailed = 0;
            listBox1.Items.Clear();
            
            DataTable datatable = CsvHelper.OpenCSV(file, 3);
           
            ThreadPool.SetMinThreads(threadPoolSize, 10);


            // 定义正则表达式用来匹配 img 标签
            Regex regImg = new Regex(@"(http.[^""<>]*(jpg|bmp|gif|png))", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnoreCase);


            // 搜索匹配的字符串
            foreach (DataRow datarow in datatable.Rows)
            {
                String sHtmlText = datarow["宝贝描述"].ToString();
                MatchCollection matches = regImg.Matches(sHtmlText);
                List<String> imgList = new List<string>();
                foreach (Match match in matches)
                {
                    if (imgList.Contains(match.Value)) continue;
                    imgList.Add(match.Value);
                }
                imgCount = imgCount + imgList.Count;

                ThreadPool.QueueUserWorkItem(new WaitCallback(DownLoad), imgList);
            }
            statusProgressBar_percent.Minimum = 0;
            statusProgressBar_percent.Maximum = imgCount;
        }

        private void DownLoad(object obj)
        {
            String savePath = textBox_savePath.Text;
          
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            List<String> imgList = obj as List<String>;
            for (int i = 0; i < imgList.Count; i++)
            {
                string url = imgList[i];
                try
                {
                    //if (File.Exists(string.Concat(savePath, "/", Path.GetFileName(url)))) //如果图片存在，则就认为是请求成功
                    //{
                    //    this.Invoke(new UpdateListBox(InsertItem), "√  " + url); 
                    //}
                    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                    WebResponse response = request.GetResponse();
                    long cLength = response.ContentLength;

                    if (cLength > 0)
                    {
                        using (Stream stream = response.GetResponseStream())
                        {
                            Image img = Image.FromStream(stream);
                            if (!File.Exists(string.Concat(savePath, "/", Path.GetFileName(url))))
                                img.Save(string.Concat(savePath, "/", Path.GetFileName(url)));
                            img.Dispose();
                            stream.Close();
                        }

                        //成功下载
                        this.Invoke(new UpdateListBox(InsertItem), "√  " + url);
                    }
                    else
                        this.Invoke(new UpdateListBox(InsertItem), "×  " + url);

                }
                catch (Exception e)
                {
                    WriteTxt(e);
                    this.Invoke(new UpdateListBox(InsertItem), "×  " + url);
                }
            }
        }

        public static void WriteTxt(Exception e)
        {
            try
            {
                String logFile = Directory.GetCurrentDirectory() + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                FileStream fs = new FileStream(logFile, System.IO.FileMode.OpenOrCreate | FileMode.Append);
                StreamWriter sWriter = new StreamWriter(fs);
                sWriter.WriteLine("\n\n\n\t 异常时间:" + DateTime.Now.ToString());
                sWriter.WriteLine(e.ToString());
                sWriter.Close();
                fs.Close();
            }
            catch (Exception)
            {
            }
        }

        private void InsertItem(String str)
        {
            string strMark = str.Substring(0, 1);
            if (strMark == "√")
            {
                imgSuccess = imgSuccess + 1;
            }
            else if (strMark == "×")
            {
                imgFailed = imgFailed + 1;
            }
            listBox1.Items.Add(str);

            status_fail.Text = String.Format("| 失败 {0} 张", imgFailed);
            status_success.Text = String.Format("| 成功 {0} 张", imgSuccess);
            status_total.Text = String.Format("| 总共 {0} 张", imgCount);
            statusProgressBar_percent.Value = imgSuccess + imgFailed;
            statusLabel_percent.Text = ((float)(imgFailed + imgSuccess) / (float)imgCount).ToString("0.00%");
        }

        private void textBox_savePath_TextChanged(object sender, EventArgs e)
        {
            //写注册表
            RegistryKey regWrite;
            regWrite = Registry.CurrentUser.CreateSubKey("Software\\DownLoadImg");
            regWrite.SetValue("browser", textBox_savePath.Text);
            //关闭该对象
            regWrite.Close();
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {

            if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();     //显示选择文件对话框
            String initDirectory = textBox_savePath.Text;
            if (String.IsNullOrEmpty(initDirectory))
                initDirectory = Directory.GetCurrentDirectory();
            openFileDialog1.InitialDirectory = initDirectory;
            openFileDialog1.Filter = "CSV文件|*.csv";
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.textBox_file.Text = openFileDialog1.FileName;          //显示文件路径

                this.textBox_savePath.Text = Path.GetDirectoryName(openFileDialog1.FileName) + "\\Image";

                //写注册表
                RegistryKey regWrite;
                regWrite = Registry.CurrentUser.CreateSubKey("Software\\DownLoadImg");
                regWrite.SetValue("fileName", textBox_file.Text);
                regWrite.SetValue("browser", textBox_savePath.Text);
                //关闭该对象
                regWrite.Close();
            }
        }

        private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            Brush FontBrush = null;
            ListBox listBox = sender as ListBox;
            if (e.Index > -1)
            {
                switch (listBox.Items[e.Index].ToString().Substring(0, 1))
                {
                    case "√": FontBrush = Brushes.Black; break;
                    case "×": FontBrush = Brushes.Red; break;
                    default: FontBrush = Brushes.Black; break;
                }
                e.DrawBackground();
                e.Graphics.DrawString(listBox.Items[e.Index].ToString(), e.Font, FontBrush, e.Bounds);
                e.DrawFocusRectangle();
            }
        }

        private void GetImgs_Load(object sender, EventArgs e)
        {

            RegistryKey regRead;
            regRead = Registry.CurrentUser.OpenSubKey("Software\\DownLoadImg", true);
            if (regRead != null)
            {
                object obj = regRead.GetValue("fileName"); //读取“fileName”项的值
                if (obj != null) textBox_file.Text = obj.ToString(); //显示在TextBox里
                obj = regRead.GetValue("browser"); //读取“browser”项的值
                if (obj != null) textBox_savePath.Text = obj.ToString(); //显示在TextBox里
                //关闭该对象
                regRead.Close();
            }
        }

        private void textBox_file_TextChanged(object sender, EventArgs e)
        {
            //写注册表
            RegistryKey regWrite;
            regWrite = Registry.CurrentUser.CreateSubKey("Software\\DownLoadImg");
            regWrite.SetValue("fileName", textBox_file.Text);
            //关闭该对象
            regWrite.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                textBox_savePath.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {

        }
    }
}
